package com.example.telesys.interceptor;


import com.example.telesys.exception.TokenExpiredException;
import com.example.telesys.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        // 获取header中的token以及对应的claims信息
        String token = request.getHeader("token");
        // 是否通过
        boolean isAllowPass = true;
        // 如果头部中的token信息为空
        if (token == null) {
            // 检查url中的token信息是否也为空
            token = request.getParameter("token");
            if(token == null){
                isAllowPass = false;
            }
        } else {
            //获取到token中的信息 并看是否过期
            if (JwtUtils.getClaimByToken(token) == null) {
                throw new TokenExpiredException("您好，您的用户信息已过期！请重新登录。");
            }
        }
        return isAllowPass;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
